import React, {useEffect} from 'react';
import {ModalForm, ProFormSelect, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import {message} from 'antd';
import {API} from "@/services/typings";
import {addSysJob, updateSysJob} from "@/pages/job/job-manager/service";
import {ProFormInstance} from "@ant-design/pro-components";

interface CreateOrEditFormProps {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  formType: 'create' | 'edit';
  currentRow?: API.ISysJob;
  onSuccess: () => void;
}

const CreateOrEditForm: React.FC<CreateOrEditFormProps> = ({
                                                             visible,
                                                             onVisibleChange,
                                                             formType,
                                                             currentRow,
                                                             onSuccess,
                                                           }) => {
  const formRef = React.useRef<ProFormInstance>();

  // 修复1: 使用useEffect监听visible和currentRow变化
  useEffect(() => {
    if (visible) {
      // 修复2: 使用setTimeout确保表单已渲染
      setTimeout(() => {
        if (formType === 'edit' && currentRow) {
          formRef.current?.setFieldsValue(currentRow);
        } else {
          formRef.current?.resetFields();
          // 修复3: 设置默认值
          formRef.current?.setFieldsValue({
            misfirePolicy: '3',
            concurrent: '1'
          });
        }
      }, 0);
    }
  }, [visible, currentRow, formType]);

  const handleSubmit = async (values: any) => {
    try {
      if (formType === 'create') {
        const {data} = await addSysJob(values);
        if (data) {
          message.success(`创建成功`);
          onVisibleChange(false);
          onSuccess();
        }
      } else {
        if (!currentRow?.jobId) {
          message.error(`请选择要编辑的定时任务`);
          return;
        }
        const {data} = await updateSysJob({
          jobId: currentRow.jobId,
          ...values,
        });
        if (data) {
          message.success(`更新成功`);
          onVisibleChange(false);
          onSuccess();
        } else {
          message.error(`更新失败`);
        }
      }
    } catch (error) {
      message.error('操作失败，请重试');
    }
  };

  return (
    <ModalForm
      title={formType === 'create' ? '新建定时任务' : '编辑定时任务'}
      width="600px"
      visible={visible}
      onVisibleChange={onVisibleChange}
      onFinish={handleSubmit}
      formRef={formRef}
      // 移除initialValues，改为使用useEffect设置
      modalProps={{
        destroyOnClose: true,  // 修复5: 关闭时销毁表单
      }}
    >
      <ProFormText
        name="jobName"
        label="任务名称"
        rules={[{required: true, message: '请输入任务名称'}]}
        placeholder="请输入任务名称"
      />

      <ProFormSelect
        name="jobGroup"
        label="任务组"
        valueEnum={{
          'DEFAULT': '默认',
          'SYSTEM': '系统',
        }}
        rules={[{required: true, message: '请选择任务组'}]}
      />

      <ProFormTextArea
        name="invokeTarget"
        label="调用目标"
        rules={[{required: true, message: '请输入调用目标'}]}
        placeholder="例如: com.example.task.TestTask.execute()"
        fieldProps={{
          rows: 3,
        }}
      />

      <ProFormText
        name="cronExpression"
        label="Cron表达式"
        rules={[{required: true, message: '请输入Cron表达式'}]}
        placeholder="例如: 0 0 2 * * ?"
        extra={
          <a
            href="https://www.bejson.com/othertools/cron/"
            target="_blank"
            rel="noopener noreferrer"
          >
            Cron表达式生成工具
          </a>
        }
      />

      <ProFormSelect
        name="misfirePolicy"
        label="错误策略"
        valueEnum={{
          '1': '立即执行',
          '2': '执行一次',
          '3': '放弃执行',
        }}
      />

      <ProFormSelect
        name="concurrent"
        label="并发执行"
        valueEnum={{
          '0': '允许',
          '1': '禁止',
        }}
      />

      <ProFormTextArea
        name="remark"
        label="备注"
        placeholder="请输入备注信息"
      />
    </ModalForm>
  );
};

export default CreateOrEditForm;
